package org.zhengquan.service;

import com.google.common.base.Preconditions;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.zhengquan.common.RequestHolder;
import org.zhengquan.dao.SysDeptMapper;
import org.zhengquan.dao.SysUserMapper;
import org.zhengquan.exception.ParamException;
import org.zhengquan.pojo.SysDept;
import org.zhengquan.util.BeanValidator;
import org.zhengquan.util.IpUtil;
import org.zhengquan.util.LevelUtil;
import org.zhengquan.vo.DeptVO;

import java.util.Date;
import java.util.List;

/**
 * @author zhengquan
 * @date 2017/10/27
 */
@Service
public class SysDeptService {

    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysLogService sysLogService;

    public void save(DeptVO deptVO) {
        BeanValidator.check(deptVO);
        if (checkExit(deptVO.getParentId(), deptVO.getId(), deptVO.getName())) {
            throw new ParamException("同一层级下存在相同名称的部门");
        }
        SysDept sysDept = SysDept.builder().name(deptVO.getName()).parentId(deptVO.getParentId())
                .seq(deptVO.getSeq()).remark(deptVO.getRemark()).build();

        sysDept.setLevel(LevelUtil.calculateLevel(getLevel(sysDept.getParentId()), sysDept.getParentId()));
        sysDept.setOperator(RequestHolder.getCurrentUser().getUsername());
        sysDept.setOperateIp(IpUtil.getRemoteIp(RequestHolder.getCurrentRequest()));
        sysDept.setOperateTime(new Date());
        sysDeptMapper.insertSelective(sysDept);
        sysLogService.saveDeptLog(null, sysDept);
    }

    public void update(DeptVO deptVO) {
        BeanValidator.check(deptVO);
        if (checkExit(deptVO.getParentId(), deptVO.getId(), deptVO.getName())) {
            throw new ParamException("同一层级下存在相同名称的部门");
        }
        SysDept before = sysDeptMapper.selectByPrimaryKey(deptVO.getId());
        Preconditions.checkNotNull(before, "待更新的部门不存在");
        SysDept after = SysDept.builder().id(deptVO.getId()).name(deptVO.getName()).parentId(deptVO.getParentId())
                .seq(deptVO.getSeq()).remark(deptVO.getRemark()).build();
        after.setLevel(LevelUtil.calculateLevel(getLevel(deptVO.getParentId()), deptVO.getParentId()));
        after.setOperator(RequestHolder.getCurrentUser().getUsername());
        after.setOperateIp(IpUtil.getRemoteIp(RequestHolder.getCurrentRequest()));
        after.setOperateTime(new Date());
        updateWithChild(before, after);
        sysLogService.saveDeptLog(before, after);
    }

    public void delete(Integer depId) {
        SysDept sysDept = sysDeptMapper.selectByPrimaryKey(depId);
        Preconditions.checkNotNull(sysDept, "待删除的部门不存在,无法删除");
        if (sysDeptMapper.countByParentId(depId) > 0) {
            throw new ParamException("当前部门下有子部门,无法删除");
        }
        if (sysUserMapper.countByDeptId(depId) > 0) {
            throw new ParamException("当前部门下有用户,无法删除");
        }
        sysDeptMapper.deleteByPrimaryKey(depId);
    }

    @Transactional(rollbackFor = Exception.class)
    private void updateWithChild(SysDept before, SysDept after) {
        String newLevelPrefix = after.getLevel();
        String oldLevelPrefix = before.getLevel();
        if (!newLevelPrefix.equals(oldLevelPrefix)) {
            List<SysDept> deptList = sysDeptMapper.selectChildDeptListByLevel(new StringBuilder(oldLevelPrefix).append(".").append(before.getId()).toString());
            if (CollectionUtils.isNotEmpty(deptList)) {
                for (SysDept sysDept : deptList) {
                    String level = sysDept.getLevel();
                    if (level.indexOf(oldLevelPrefix) == 0) {
                        level = newLevelPrefix + level.substring(oldLevelPrefix.length());
                        sysDept.setLevel(level);
                    }
                }
                sysDeptMapper.batchUpdateLevel(deptList);
            }
        }
        sysDeptMapper.updateByPrimaryKey(after);
    }

    private boolean checkExit(Integer parentId, Integer deptId, String deptName) {
        return sysDeptMapper.countByNameAndParentId(parentId, deptId, deptName) > 0;
    }

    private String getLevel(Integer deptId) {
        SysDept sysDept = sysDeptMapper.selectByPrimaryKey(deptId);
        if (sysDept == null) {
            return null;
        }
        return sysDept.getLevel();
    }
}
